import {AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {StatusEnum} from '../../../core/enum/status.enum';
import {NzMessageService} from 'ng-zorro-antd';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {StorageUtil} from '../../../utils/storage.util';
import {OtherUtil} from '../../../utils/other.util';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { CourseManageService } from './course-manage.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FilterEnum, FilterTypeEnum } from '../../../core/enum/filter.enum';
import { DatePipe } from '@angular/common';
import { PostDown } from '../../../utils/postdown';

declare var $: any;

@Component({
  selector: 'app-course-manage',
  templateUrl: './course-manage.component.html',
  styleUrls: ['./course-manage.component.scss'],
  providers: [CourseManageService, PostDown]
})
/**********课程管理*************/
export class CourseManageComponent implements OnInit {
  topSearch: TopSearchObj = new TopSearchObj();
  pageInfo: PageEntity = new PageEntity();
  allList = [];
  displayList: Array<any> = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = false;
  nzWidthConfigs = [];
  yearListSearch = [];
  semestSearch = [];

  // 新增
  validateForm: FormGroup;
  addObj: AddObj = new AddObj();
  yearList = []; // 学年
  semesterList = [];
  teacherList = [];
  collogeList = [];
  marjorList = [];
  classList = [];

  mainStatus = 1; // 1.显示主页面，2.显示新增页面,3:发布评价,4:学生详情
  isEdit = false;
  // 发布评价
  checked = false;
  stuList = [];
  schoolList = [];
  departList = [];
  pubObj: PubObj = new PubObj();
  pubObjStu: DeptObj = new DeptObj();
  pubObjSchool: DeptObj = new DeptObj();
  pubObjDept: DeptObj = new DeptObj();

  user = null;
  isStudent = true; // 学生评价是否显示
  isDepartShow = false; // 系部评价是否显示
  isSchoolShow = false; // 校级评价是否显示
  isDepart = false; // 系部评价是否显示，同时为true表明不是普通老师
  isSchool = false; // 督导评价校级评价是否显示
  defaultTable = null; // 默认评价表
  countField = ['deptEvaluateCount', 'superviseEvaluateCount'];
  countAuthField = [];

  // 学生详情
  pageInfoStu: PageEntity = new PageEntity();
  allListStu = [];
  constructor(
    private service: CourseManageService,
    private message: NzMessageService,
    private cd: ChangeDetectorRef,
    private ref: ElementRef,
    private httpclient: HttpClient,
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private postDown: PostDown
  ) {
  }

  ngOnInit() {
    this.getPageCols();
    this.initForm();
    this.getYearSearch();

    this.user = StorageUtil.getLocalStorage('user');
    if (this.user && this.user.teacher.roles) { // 判断校级领导和超管显示督导评价
      this.isSchoolShow = this.user.teacher.roles.indexOf('校领导') > -1 || this.user.teacher.roles.indexOf('超级管理员') > -1;
      this.isDepartShow = this.user.teacher.roles.indexOf('校领导') > -1 || this.user.teacher.roles.indexOf('超级管理员') > -1 || this.user.teacher.roles.indexOf('系部领导') > -1;
    }
  }

  initForm() {
    this.validateForm = this.fb.group({
      address: [null, [Validators.required]],
      classesIdList: [null, [Validators.required]],
      majorId: [null, [Validators.required]],
      name: [null, [Validators.required]],
      number: [null, [Validators.required]],
      sectionCount: [null, [Validators.required]],
      semesterId: [null, [Validators.required]],
      schoolYearId: [null, [Validators.required]],
      startDeptId: [null, [Validators.required]],
      teachDeptId: [null, [Validators.required]],
      teacherId: [null, [Validators.required]],
      type: [null, [Validators.required]],
      teacherNumber: [null, []],
      teacherTitle: [null, []],
    });
  }

  getPageCols() {
    this.service.getPageColsApi().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.countAuthField = res.datas;
      }
      this.page(this.pageInfo);
    });
  }

  /**
   * 查询学年学期列表
   */
  getYearSearch() {
    this.service.year().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.yearListSearch = res.datas;
        this.semestSearch = [];
      }
    });
  }

  yearSearchChange(e) {
    this.topSearch.semesterId = null;
    this.yearListSearch.forEach(item => {
      if (e == item.schoolYear) {
        this.semestSearch = item.semester;
      }
    });
  }

  /*****分页查询*********/
  page(page: PageEntity): void {
    page.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.service.getPage(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
        let widthNumber = 0;
        this.countAuthField.map(item => {
          if (this.countField.includes(item)) {
            widthNumber ++;
          }
        });
        // this.nzWidthConfigs = ['60px', '150px', '100px', '150px', '150px', '100px', '100px', '180px', '100px', '100px', '100px', '150px',
        // '200px', '300px', '180px'];
        this.nzWidthConfigs = ['60px', '150px', '100px', '150px', '150px', '100px', '100px', '180px', '100px', '100px', '100px', '180px'];
        for (let i = 0; i < widthNumber; i++) {
          this.nzWidthConfigs.push('150px');
        }
        this.nzWidthConfigs.push('150px');
        this.nzWidthConfigs.push('180px');
      }
    });
  }


  /*******第几页*******/
  searchPageIndex(event: any) {
    this.pageInfo.first = event;
    this.page(this.pageInfo);
  }

  /*******每页几条*****/
  searchPageSize(event: any) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /*******状态改变******/
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  /**
   * 全选
   * @param value： value
   */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  /**
   * 主页根据id删除逻辑
   */
  delByIdsLogic() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    return arr;
  }

  /******删除所选********/
  deleteAll() {
    const arr = this.delByIdsLogic();
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据！');
      return;
    }
    this.service.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.pageInfo.first = 1;
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  cancelFn(): void {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }


  /**
   * 点击删除一个
   * @param ids： id
   */
  deleteOne(ids: string) {
    this.service.delete(ids).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  /********判断是否选择了数据需要删除**********/
  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /*******点击查询*********/
  clickSearch() {
    this.pageInfo.first = 1;
    for (const o in this.topSearch) {
      if (o === 'semesterId' || o === 'schoolYear') {
        if (this.topSearch[o]) {
          this.pageInfo.filters[o] = PaginationUtils.filters(this.topSearch[o], FilterEnum.EQUALS);
        } else {
          delete this.pageInfo.filters[o];
        }
      } else {
        if (this.topSearch[o]) {
          this.pageInfo.filters[o] = PaginationUtils.filters(this.topSearch[o], FilterEnum.CONTAINS);
        } else {
          delete this.pageInfo.filters[o];
        }
      }
    }
    this.page(this.pageInfo);
  }

  /********点击重置**************/
  resetSearch() {
    this.pageInfo = new PageEntity();
    this.topSearch = new TopSearchObj();
    this.semestSearch = [];
    this.page(this.pageInfo);
  }

  /******点击新增业务逻辑处理部分,初始化数据显示部分*********/
  clickAdd() {
    this.isEdit = true;
    this.teacherList = [];
    this.mainStatus = 2;
    this.addObj = new  AddObj();
    this.initForm();
    this.getYearSemes();
    this.getColleges();
    setTimeout(() => {
      this.isEdit = false;
    }, 2000);
  }

  departChange(e) {
    if (this.isEdit) { // 编辑时,进入页面时不需要清空值
    } else {
      this.addObj.teacherId = null;
      this.addObj.teacherNumber = null;
      this.addObj.teacherTitle = null;
      this.teacherList = [];
      this.getTeachLists(e);
    }
  }

  /**
   * 查询老师
   */
  getTeachLists(rid) {
    const ft = {
      orgId: {
        matchMode: FilterEnum.EQUALS,
        value: rid,
        whereType: FilterTypeEnum.AND
      }
    };
    this.service.getTeachList({ filters: ft}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.teacherList = res.datas;
      }
    });
  }

  teacherListChange(e) {
    this.teacherList.forEach(item => {
      if (e === item.id) {
        this.addObj.teacherNumber = item.number;
        this.addObj.teacherTitle = item.title;
      }
    });
  }

  /**
   * 查询学年学期列表
   */
  getYearSemes() {
    this.service.year().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.yearList = res.datas;
        if (this.isEdit) { // 编辑时
          this.yearList.forEach(item => {
            if (this.addObj.schoolYearId == item.schoolYear) {
              this.semesterList = item.semester;
            }
          });
        } else {
          this.semesterList = [];
        }
      }
    });
  }

  yearListChange(e) {
    if (this.isEdit) { // 编辑时,进入页面时不需要清空值
    } else {
      this.addObj.semesterId = null;
      this.yearList.forEach(item => {
        if (e == item.schoolYear) {
          this.semesterList = item.semester;
        }
      });
    }
  }

  /**
   * 查询学院
   */
  getColleges() {
    this.service.getCollege().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.collogeList = res.datas;
      }
    });
  }

  /**
   * 查询专业
   */
  getMajors(rid) {
    this.service.getMajor(rid).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.marjorList = res.datas;
      }
    });
  }

  /**
   * 查询班级
   */
  getClasss(rid) {
    this.service.getClass(rid).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.classList = res.datas;
      }
    });
  }

  collChange(e) {
    if (this.isEdit) { // 编辑时,进入页面时不需要清空值
    } else {
      this.addObj.majorId = null;
      this.addObj.classesIdList = [];
      this.getMajors(e);
    }
  }

  majorChange(e) {
    if (this.isEdit) { // 编辑时,进入页面时不需要清空值
    } else {
      this.addObj.classesIdList = [];
      this.getClasss(e);
    }
  }


  // 新增编辑确定
  creatClick() {
    const opt = this.addObj.id ? 'update' : 'create';
    this.service[opt](this.addObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.mainStatus = 1;
        this.page(this.pageInfo);
      }
    });
  }

  /**
   * 点击编辑
   */
  edit(data) {
    this.isEdit = true;
    this.mainStatus = 2;
    this.initForm();
    this.getYearSemes();
    this.getColleges();
    this.addObj = JSON.parse(JSON.stringify(data));
    this.addObj.schoolYearId = this.addObj.schoolYear;
    const arry = [];
    this.addObj.classesList.forEach(cla => {
      arry.push(cla.classesId);
    });
    this.addObj.classesIdList = arry;
    this.getTeachLists(this.addObj.startDeptId);
    this.getMajors(this.addObj.teachDeptId);
    this.getClasss(this.addObj.majorId);
    setTimeout(() => {
      this.isEdit = false;
    }, 2000);
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
  exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      const arr = this.delByIdsLogic();
      if (arr.length < 1) {
        this.message.warning('请勾选要导出的数据！');
        return;
      }
      obj.pager = {};
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfo;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('evalute-server/evalute/base/course/exportExcel', obj);
  }

  // 发布评价
  publish(data) {
    this.isStudent = true;
    this.isDepart = false;
    this.isSchool = false;
    this.service.getDef().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.defaultTable = res.datas;
        if (!this.isDepartShow) { // 是普通老师
          if (!this.defaultTable) { // 返回null
            this.message.warning('暂未设置默认评价表！');
            return;
          }
        }
        this.pubObj = new PubObj();
        this.pubObjStu = new DeptObj();
        this.pubObjSchool = new DeptObj();
        this.pubObjDept = new DeptObj();
        if (data) {
          this.pubObj.courseIdList = [data.id];
        } else {
          const arr = this.delByIdsLogic();
          if (arr.length < 1) {
            this.message.warning('请勾选要发布的数据！');
            return;
          }
          this.pubObj.courseIdList = arr;
        }

        this.mainStatus = 3;
        this.getStuList(data);
      }
    });
  }

  setStuDef(e) {
    if (e) {
      this.pubObjStu.isDefault = true;
    }
  }

  getStuList(data) {
    this.service.stuList({}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.stuList = res.datas;
        if (this.defaultTable) {
          this.pubObjStu.id = this.defaultTable.id;
          this.pubObjStu.isDefault = true;
        }
      }
    });

    let val1 = null;
    if (data && data.startDeptId) {
      val1 = data.startDeptId;
    }
    if (data && data.teachDeptId) {
      val1 = val1 + ',' + data.teachDeptId;
    }
    if (this.isDepartShow) {
      const ft1 = {
        type: {
          matchMode: FilterEnum.EQUALS,
          value: '系部督导',
          whereType: FilterTypeEnum.AND
        }
      };
      if (val1) {
        ft1['deptId'.toString()] = {
          matchMode: FilterEnum.IN,
          value: val1,
          whereType: FilterTypeEnum.AND
        };
      }
      this.service.schoolList({
        cols: ['id', 'name'],
        filters: ft1
      }).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.departList = res.datas;
        }
      });
    }

    if (this.isSchoolShow) {
      const ft = {
        type: {
          matchMode: FilterEnum.EQUALS,
          value: '校级督导',
          whereType: FilterTypeEnum.AND
        }
      };
      this.service.schoolList({
        cols: ['id', 'name'],
        filters: ft
      }).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.schoolList = res.datas;
        }
      });
    }
  }

  schChange(e) {
    if (e) {
      this.pubObjSchool.timeArry = [];
    }
  }
  depChange(e) {
    if (e) {
      this.pubObjDept.timeArry = [];
    }
  }
  stuChange(e) {
    if (e) {
      this.pubObjStu.timeArry = [];
    }
  }

  surePublish() {
    if (!this.isStudent && !this.isDepart && !this.isSchool) {
      this.message.warning('必须选择一个评价!');
      return;
    }
    if (this.isStudent) {
      if (!this.pubObjStu.id) {
        this.message.warning('学生评价评价表不能为空!');
        return;
      }
      if (this.pubObj.courseIdList.length > 1) {
        if (!this.pubObjStu.minSectionCount) {
          this.message.warning('课时不能为空!');
          return;
        }
      }
      if (!this.pubObjStu.noLimitDate) {
        if (this.pubObjStu.timeArry && this.pubObjStu.timeArry.length > 0) {
          this.pubObjStu.startDate = this.datePipe.transform(this.pubObjStu.timeArry[0], 'yyyy-MM-dd');
          this.pubObjStu.endDate = this.datePipe.transform(this.pubObjStu.timeArry[1], 'yyyy-MM-dd');
        } else {
          this.pubObjStu.startDate = null;
          this.pubObjStu.endDate = null;
          this.message.warning('学生评价评价时间限时时，时间必选!');
          return;
        }
      } else {
        this.pubObjStu.timeArry = [];
        this.pubObjStu.startDate = null;
        this.pubObjStu.endDate = null;
        this.pubObjStu.noLimitDate = Number(this.pubObjStu.noLimitDate);
      }
      this.pubObjStu.isDefault = Number(this.pubObjStu.isDefault);
      this.pubObj.student = this.pubObjStu;
    }

    if (this.isDepart) {
      if (!this.pubObjDept.id) {
        this.message.warning('系部评价评价表不能为空!');
        return;
      }
      if (!this.pubObjDept.noLimitDate) {
        if (this.pubObjDept.timeArry && this.pubObjDept.timeArry.length > 0) {
          this.pubObjDept.startDate = this.datePipe.transform(this.pubObjDept.timeArry[0], 'yyyy-MM-dd');
          this.pubObjDept.endDate = this.datePipe.transform(this.pubObjDept.timeArry[1], 'yyyy-MM-dd');
        } else {
          this.pubObjDept.startDate = null;
          this.pubObjDept.endDate = null;
          this.message.warning('系部评价评价时间限时时，时间必选!');
          return;
        }
      } else {
        this.pubObjDept.timeArry = [];
        this.pubObjDept.startDate = null;
        this.pubObjDept.endDate = null;
        this.pubObjDept.noLimitDate = Number(this.pubObjDept.noLimitDate);
      }
      this.pubObj.dept = this.pubObjDept;
    }

    if (this.isSchool) {
      if (!this.pubObjSchool.id) {
        this.message.warning('督导评价评价表不能为空!');
        return;
      }
      if (!this.pubObjSchool.noLimitDate) {
        if (this.pubObjSchool.timeArry && this.pubObjSchool.timeArry.length > 0) {
          this.pubObjSchool.startDate = this.datePipe.transform(this.pubObjSchool.timeArry[0], 'yyyy-MM-dd');
          this.pubObjSchool.endDate = this.datePipe.transform(this.pubObjSchool.timeArry[1], 'yyyy-MM-dd');
        } else {
          this.pubObjSchool.startDate = null;
          this.pubObjSchool.endDate = null;
          this.message.warning('督导评价评价时间限时时，时间必选!');
          return;
        }
      } else {
        this.pubObjSchool.timeArry = [];
        this.pubObjSchool.startDate = null;
        this.pubObjSchool.endDate = null;
        this.pubObjSchool.noLimitDate = Number(this.pubObjSchool.noLimitDate);
      }
      this.pubObj.school = this.pubObjSchool;
    }
    this.service.setEvalute(this.pubObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.mainStatus = 1;
        this.page(this.pageInfo);
      }
    });
  }

  // 学生详情
  studentClick(data) {
    this.mainStatus = 4;
    this.pageInfoStu = new PageEntity();
    this.pageInfoStu.filters['courseId'.toString()] = PaginationUtils.filters(data.id, FilterEnum.EQUALS);
    this.getPageStu(this.pageInfoStu);
  }


  /*****学生详情分页查询*********/
  getPageStu(page: PageEntity): void {
    this.service.pageForStudent(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allListStu = res.datas.data;
        this.pageInfoStu.totalRecords = res.datas.totalRecords;
      }
    });
  }

  // 新增编辑返回
  back() {
    this.mainStatus = 1;
  }
}

class TopSearchObj {
  semesterId?: string;
  schoolYear?: string;
  name?: string;
  teacherName?: string;
  classesName?: string;
}

class AddObj {
  id?: string;
  address?: string;
  classesIdList?: any;
  classesList?: any;
  majorId?: string;
  name?: string;
  number?: string;
  sectionCount?: number;
  schoolYearId?: string;
  schoolYear?: string;
  semesterId?: string;
  startDeptId?: string; // 开课部门id
  teachDeptId?: string; // 授课部门id
  teacherId?: string;
  type?: string; // 类型：专业课、通识课
  teacherNumber?: string; // 工号
  teacherTitle?: string; // 职称
}

class PubObj {
  courseIdList?: any; // 课程idList
  dept?: any;
  school?: any;
  student?: any;
}

class DeptObj {
  endDate?: string;
  id?: string; // 模板id
  isDefault?: any; // 学生评价表模板 - 是否设置默认
  minSectionCount?: any; // 学生评价表模板 - 限制课节数量
  noLimitDate?: any; // 不限制时间
  startDate?: string; // 评价开始时间
  timeArry?: any;
}
